using B.S.Meeting.Infrastructure.Interfaces;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using System;
using System.Threading.Tasks;

namespace B.S.Meeting.Infrastructure.Implements
{
    public class VerificationCodeService : IVerificationCodeService
    {
        private readonly IMemoryCache _cache;
        private readonly ILogger<VerificationCodeService> _logger;
        private const int CODE_LENGTH = 6;
        private const int CODE_EXPIRATION_MINUTES = 5;

        public VerificationCodeService(IMemoryCache cache, ILogger<VerificationCodeService> logger)
        {
            _cache = cache ?? throw new ArgumentNullException(nameof(cache));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
        }

        public async Task<string> GenerateCodeAsync(string phone)
        {
            try
            {
                // 生成6位随机验证码
                Random random = new Random();
                string code = random.Next(100000, 999999).ToString();

                // 存储验证码，设置5分钟过期
                var cacheKey = $"VerificationCode_{phone}";
                _cache.Set(cacheKey, code, TimeSpan.FromMinutes(CODE_EXPIRATION_MINUTES));

                _logger.LogInformation($"为手机号 {phone} 生成验证码: {code}");
                return code;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"生成验证码失败: {phone}");
                throw;
            }
        }

        public async Task<bool> ValidateCodeAsync(string phone, string code)
        {
            try
            {
                var cacheKey = $"VerificationCode_{phone}";
                if (_cache.TryGetValue(cacheKey, out string storedCode))
                {
                    bool isValid = storedCode == code;
                    if (isValid)
                    {
                        _logger.LogInformation($"手机号 {phone} 验证码验证成功");
                    }
                    else
                    {
                        _logger.LogWarning($"手机号 {phone} 验证码验证失败，输入: {code}, 存储: {storedCode}");
                    }
                    return isValid;
                }

                _logger.LogWarning($"手机号 {phone} 验证码不存在或已过期");
                return false;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"验证码验证失败: {phone}");
                return false;
            }
        }

        public async Task RemoveCodeAsync(string phone)
        {
            try
            {
                var cacheKey = $"VerificationCode_{phone}";
                _cache.Remove(cacheKey);
                _logger.LogInformation($"移除手机号 {phone} 的验证码");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"移除验证码失败: {phone}");
                throw;
            }
        }
    }
} 